#!/bin/bash
#setup proxy server for various applications..

export TEXTDOMAIN=proxy-setup
export OUTPUT_CHARSET=UTF-8

#set -x

usage() {
	app=${0##*/}
	echo
	echo "  setup proxy server for various applications.."
	echo
	echo "usage: $app <option> [param]"
	echo
	echo "Options:"
	echo " -cli           : force cli"
	echo " -gui           : force gui"
	echo " -sysroot <root>: set root dir"
	echo " -set <proxy>   : set proxy (unattended)"
	echo " -unset         : unset proxy (unattended)"
	echo " -status        : report status"
	echo
	echo "Examples:"
	echo "  $app -set http://proxy.com:8080"
	echo "  $app -set 192.168.0.1:8080"
	echo "  $app -set http://user:pass@180.190.200.210:80"
	echo 
}

#====================================================================

PROXY_SERVER_FILE='/etc/profile.d/proxy_setup'

msg_proxy="$(gettext 'You have modified the proxy server settings. Note, you can see the result in files /etc/profile.d/proxy_setup. However, MOST IMPORTANT, you must reboot for this to take effect')"
msg_noproxy="$(gettext 'You have chosen NOT to use a proxy server. Note, if you previously did have a proxy server enabled, you MUST REBOOT for the change to take effect')"
msg_unset="$(gettext "You can revert this now by typing 'proxy-setup -unset'")"

set_proxy() {
	if [ ! "$1" ] ; then
		echo "Missing param"
		usage
		return 1
	fi
	p_r_o_x_y="$1"
	grep -q '://' <<< ${p_r_o_x_y} || p_r_o_x_y="http://${p_r_o_x_y}"
	echo;echo "Setting $p_r_o_x_y as the proxy server..."; echo
	(
		echo "export http_proxy='${p_r_o_x_y}'"
		echo "export https_proxy='${p_r_o_x_y}'"
		echo "export rsync_proxy='${p_r_o_x_y}'"
		echo "export ftp_proxy='${p_r_o_x_y}'"
		echo "export ftps_proxy='${p_r_o_x_y}'"
		echo "export HTTP_PROXY='${p_r_o_x_y}'"
		echo "export HTTPS_PROXY='${p_r_o_x_y}'"
		echo "export RSYNC_PROXY='${p_r_o_x_y}'"
		echo "export FTP_PROXY='${p_r_o_x_y}'"
		echo "export FTPS_PROXY='${p_r_o_x_y}'"
	) > ${SYSROOT}${PROXY_SERVER_FILE}
	echo -n "${p_r_o_x_y}" > ${SYSROOT}/var/local/proxy_server
	echo $msg_proxy
	echo $msg_unset
}

unset_proxy() {
	rm -f ${SYSROOT}${PROXY_SERVER_FILE}
	echo $msg_noproxy
}

proxy_status() {
	echo
	if [ -f ${SYSROOT}${PROXY_SERVER_FILE} ] ; then
		echo -n "Proxy currently enabled"
		retc=0
		if [ ! "$http_proxy" ] ; then
			echo -n " but you need to restart the PC to apply the changes.."
			retc=1
		fi
	else
		echo -n "Proxy currently disabled"
		retc=2
		if [ "$http_proxy" ] ; then
			echo -n " but you need to restart the PC to apply the changes.."
			retc=3
		fi
	fi
	echo
	return $retc
}

#=========================================================================

# old files
[ -f ${SYSROOT}/etc/profile.d/ftp_proxy ] && rm -f ${SYSROOT}/etc/profile.d/ftp_proxy
[ -f ${SYSROOT}/etc/profile.d/http_proxy ] && rm -f ${SYSROOT}/etc/profile.d/http_proxy

[ "$DISPLAY" ] && GUI=1

for i in $@; do
	case $1 in
		-sysroot) SYSROOT=$2 ; shift ;;
		-set)   set_proxy $2 ; exit  ;;
		-unset) unset_proxy  ; exit $?  ;;
		-status) proxy_status; exit  ;;
		-h|-help|--help) usage; exit ;;
		-cli|cli) GUI=  ;;
		-gui|gui) GUI=1 ;;
		*) echo "unknown option: $1" ; usage ; exit 1 ;;
	esac
	shift
done

# the script can easily end here..
#=========================================================================

TITLE=$(gettext 'Proxy server setup')

ENABLE_PROXY=false
PROXY_SERVER="http://foo.org"
PORT=8080

if [ -f "${SYSROOT}$PROXY_SERVER_FILE" ] ; then
	ENABLE_PROXY=true
fi

split_protocol_and_server() {
	case "$1" in
		"http:"*)  PRTCL="http://"  ; PRX=${1//http:\/\/}  ;;
		"https:"*) PRTCL="https://" ; PRX=${1//https:\/\/} ;;
		"ftp:"*)   PRTCL="ftp://"   ; PRX=${1//ftp:\/\/}   ;;
		"ftps:"*)  PRTCL="ftp://"   ; PRX=${1//ftps:\/\/}  ;;
		*)         PRTCL="http://"  ; PRX=${1//http:\/\/}  ;;
	esac
	echo $PRTCL $PRX
}

gui_set_proxy() { #proxy port username pass
	local PROXY_SERVER=$1 PORT=$2 USERNAME=$3 PASS=$4
	if [ ! "$PROXY_SERVER" ] ; then
		if [ "$GUI" ] ; then
			/usr/lib/gtkdialog/box_ok "$TITLE" error "$(gettext 'You must specify a proxy server')"
		else
			msgbox "$(gettext 'You must specify a proxy server')"
		fi
		return 1
	fi
	if [ ! "$PORT" ] || ! [[ $PORT =~ ^[0-9]+$ ]] ; then
		if [ "$GUI" ] ; then
			/usr/lib/gtkdialog/box_ok "$TITLE" error "$(gettext 'You must specify a port number')"
		else
			msgbox "$(gettext 'You must specify a port number')"
		fi
		return 1
	fi
	if [ "$PASS1" != "$PASS2" ] ; then
		if [ "$GUI" ] ; then
			/usr/lib/gtkdialog/box_ok "$TITLE" error "$(gettext 'Sorry, the password entries are not the same')"
		else
			msgbox "$(gettext 'Sorry, the password entries are not the same')"
		fi
		return 1
	fi
	if [ "$PASS1" -a ! "$USERNAME" ] ; then
		if [ "$GUI" ] ; then
			/usr/lib/gtkdialog/box_ok "$TITLE" error "$(gettext 'You must specify a username')"
		else
			msgbox "$(gettext 'You must specify a username')"
		fi
		return 1
	fi
	#--
	read PROTOCOL HOSTNAME <<< $(split_protocol_and_server $PROXY_SERVER)
	if [ "$USERNAME" ] ; then
		if [ "$PASS" ] ; then
			PROXY="${USERNAME}:${PASS}@${HOSTNAME}:${PORT}"
		else
			PROXY="${USERNAME}@${HOSTNAME}:${PORT}"
		fi
	else
		PROXY="${HOSTNAME}:${PORT}"
	fi
	#--
	set_proxy ${PROTOCOL}${PROXY}
	if [ "$GUI" ] ; then 
		/usr/lib/gtkdialog/box_ok "$TITLE" info "$msg_proxy"
	else
		msgbox "$msg_proxy"
	fi
	return 0
}

if [ -f ${SYSROOT}/var/local/proxy_server ] ; then
	read ps < ${SYSROOT}/var/local/proxy_server
	read PROTOCOL PROXY <<< $(split_protocol_and_server $ps)
	if grep -q '@' <<< "${PROXY}" ; then
		IFS="@" read -r userpass addressport <<< "${PROXY}"
		IFS=":" read -r USERNAME PASS <<< "${userpass}"
		IFS=":" read -r HOSTNAME PORT <<< "${addressport}"
		PROXY_SERVER=${PROTOCOL}${HOSTNAME}
	else
		IFS=":" read -r HOSTNAME PORT <<< "${PROXY}"
		PROXY_SERVER=${PROTOCOL}${HOSTNAME}
	fi
fi

#=========================================================================
#                                CLI
#=========================================================================

dlg() {
	local ret file=/tmp/proxysetup$$
	dialog --backtitle "Proxy Setup" "$@" >/dev/tty 2> $file
	ret=$?
	retstr="$(cat $file)" # can be multiple lines
	rm -f $file
	return $ret
}

msgbox() { dlg --msgbox "$*" 0 0 ; }
infobox() { dlg --infobox "$*" 0 0 ; }

if [ ! "$GUI" ] ; then
	eval dlg --menu "'$(gettext 'Proxy Setup')'" 0 0 0 \
		enable     "'$(gettext 'Enable')'" \
		disable "'$(gettext 'Disable')'" \
		exit "'$(gettext 'Exit')'" || exit
	case $retstr in
		enable)  set_dlg=1 ;;
		disable) unset_proxy ;;
		exit) exit ;;
	esac
	[ "$set_dlg" ] || exit
	#--
	while [ 1 ] ; do
		dlg --form "Proxy server setup" 0 0 0 \
		"Hostname" 1 1 "$HOSTNAME"      1 20 16 0 \
		"Port"     2 1 "$PORT"          2 20 16 0 \
		"Username" 3 1 "$USERNAME"      3 20 16 0 \
		"Password" 4 1 "$PASS"          4 20 16 0 || exit 1
		while [ 1 ] ; do
			read PROXY_SERVER
			read PORT
			read USERNAME
			read PASS
			break
		done <<< "$retstr" #include lines
		# store the config
		if gui_set_proxy "$PROXY_SERVER" "$PORT" "$USERNAME" "$PASS" ; then
			break
		fi
	done
	exit
fi

#=========================================================================
#                                GUI
#=========================================================================

while [ 1 ] ; do

	#-- DEFAULTS --

	DEFAULT_PROXY_SERVER=""
	DEFAULT_USERNAME=""
	DEFAULT_PASS1=""
	DEFAULT_PASS2=""

	[ "$PROXY_SERVER" != "" ] && DEFAULT_PROXY_SERVER="<default>${PROXY_SERVER}</default>"
	[ "$USERNAME" != "" ] && DEFAULT_USERNAME="<default>${USERNAME}</default>"
	[ "$PORT" != "" ] && DEFAULT_PORT="<default>${PORT}</default>"
	if [ "$PASS" != "" ] ; then
		DEFAULT_PASS1="<default>${PASS}</default>"
		DEFAULT_PASS2="<default>${PASS}</default>"
	fi
	[ "$PASS1" != "" ] && DEFAULT_PASS1="<default>${PASS1}</default>"
	[ "$PASS2" != "" ] && DEFAULT_PASS2="<default>${PASS2}</default>"

	#-- DIALOG
	MSG1=$(gettext 'If you connect to the Internet through a proxy server, tick the checkbox and fill in the fields, (leave Username/Password blank if not needed)')
	export PROXY_SETUP_WINDOW='<window title="'${TITLE}'" icon-name="gtk-network" window-position="1">
<vbox space-expand="true" space-fill="true">
	'$(/usr/lib/gtkdialog/xml_info fixed /usr/local/lib/X11/pixmaps/www48.png 48 "$MSG1")'
	<checkbox active="'${ENABLE_PROXY}'">
		<label>'$(gettext 'Enable Internet connection through proxy server')'</label>
		<variable>ENABLE_PROXY</variable>
		<action>if true enable:PROXY_SERVER</action>
		<action>if true enable:PORT</action>
		<action>if true enable:USERNAME</action>
		<action>if true enable:PASS1</action>
		<action>if true enable:PASS2</action>
		<action>if false disable:PROXY_SERVER</action>
		<action>if false disable:USERNAME</action>
		<action>if false disable:PORT</action>
		<action>if false disable:PASS1</action>
		<action>if false disable:PASS2</action>
	</checkbox>
	<frame '$(gettext 'Proxy Server')'>
		<hbox>
			<text xalign="0" space-expand="false"><label>'$(gettext 'Hostname:')'</label></text>
			<entry space-expand="true" sensitive="'${ENABLE_PROXY}'">
				<variable>PROXY_SERVER</variable>
				'${DEFAULT_PROXY_SERVER}'
			</entry>
		</hbox>
		<hbox>
			<text xalign="0" space-expand="false"><label>'$(gettext 'Port:')'</label></text>
			<entry space-expand="true" sensitive="'${ENABLE_PROXY}'">
				<variable>PORT</variable>
				'${DEFAULT_PORT}'
			</entry>
		</hbox>
	</frame>
	<frame '$(gettext 'Proxy Authentification')'>
		<hbox>
			<text xalign="0" space-expand="false"><label>'$(gettext 'Username:')'</label></text>
			<entry space-expand="true" sensitive="'${ENABLE_PROXY}'">
				<variable>USERNAME</variable>
				'${DEFAULT_USERNAME}'
			</entry>
		</hbox>
		<hbox space-expand="true" space-fill="true">
			<text xalign="0" space-expand="false"><label>'$(gettext 'Password:')'</label></text>
			<entry space-expand="true" caps-lock-warning="true"  tooltip-markup="'$(gettext 'Enter password')'" visibility="false" sensitive="'${ENABLE_PROXY}'">
				<variable>PASS1</variable>
				'${DEFAULT_PASS1}'
			</entry>
		</hbox>
		<hbox space-expand="true" space-fill="true">
			<text xalign="0" space-expand="false"><label>'$(gettext 'Confirm password:')'</label></text>
			<entry caps-lock-warning="true"  tooltip-markup="'$(gettext 'Enter password')'" visibility="false" sensitive="'${ENABLE_PROXY}'">
				<variable>PASS2</variable>
				'${DEFAULT_PASS2}'
			</entry>
		</hbox>
	</frame>
	<hbox>
		<button>
			'$(/usr/lib/gtkdialog/xml_button-icon ok)'
			<label>'$(gettext 'OK')'</label>
			<action type="exit">OK</action>
		</button>
		<button>
			'$(/usr/lib/gtkdialog/xml_button-icon cancel)'
			<label>'$(gettext 'Cancel')'</label>
			<action type="exit">Cancel</action>
		</button>
	</hbox>
</vbox>

</window>
'

	. /usr/lib/gtkdialog/xml_info gtk
	I=$IFS; IFS=""
	for STATEMENTS in  $(gtkdialog --center --program PROXY_SETUP_WINDOW); do
		eval $STATEMENTS
	done
	IFS=$I

	[ "$EXIT" != "OK" ] && break

	if [ "$ENABLE_PROXY" = "true" ] ; then
		# store the config
		if gui_set_proxy "$PROXY_SERVER" "$PORT" "$USERNAME" "$PASS" ; then
			break
		fi
	else
		/usr/lib/gtkdialog/box_ok "$TITLE" info "$msg_noproxy"
		unset_proxy
		break
	fi

done

### END ###
